"""
初始化配置数据库脚本
将config.py中的数据导入到数据库中
"""
import sys
import os
from datetime import datetime
import logging

# 添加项目根目录到PATH
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

from backend.database.database import SessionLocal, engine
from backend.data_clean.models import (
    BrandConfig, CommonProductName, UnitConfig, 
    MarketingWordConfig, SystemConfig
)
from backend.data_clean.config import BRANDS, UNITS, REMOVE_WORDS, SPECIFICATION_PATTERN, BRAND_CHAR_RANGE

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 水果和常见商品名称列表
COMMON_PRODUCT_NAMES = [
    # 水果类
    {"name": "苹果", "category": "水果", "description": "常见水果"},
    {"name": "香蕉", "category": "水果", "description": "常见水果"},
    {"name": "橙子", "category": "水果", "description": "常见水果"},
    {"name": "葡萄", "category": "水果", "description": "常见水果"},
    {"name": "西瓜", "category": "水果", "description": "常见水果"},
    {"name": "草莓", "category": "水果", "description": "常见水果"},
    {"name": "樱桃", "category": "水果", "description": "常见水果"},
    {"name": "菠萝", "category": "水果", "description": "常见水果"},
    {"name": "芒果", "category": "水果", "description": "常见水果"},
    {"name": "猕猴桃", "category": "水果", "description": "常见水果"},
    {"name": "柚子", "category": "水果", "description": "常见水果"},
    {"name": "梨", "category": "水果", "description": "常见水果"},
    {"name": "桃", "category": "水果", "description": "常见水果"},
    {"name": "李子", "category": "水果", "description": "常见水果"},
    {"name": "柿子", "category": "水果", "description": "常见水果"},
    
    # 蔬菜类
    {"name": "番茄", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "黄瓜", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "土豆", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "胡萝卜", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "白菜", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "菠菜", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "南瓜", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "茄子", "category": "蔬菜", "description": "常见蔬菜"},
    {"name": "豆腐", "category": "蔬菜", "description": "豆制品"},
    {"name": "豆芽", "category": "蔬菜", "description": "常见蔬菜"},
    
    # 肉类
    {"name": "牛肉", "category": "肉类", "description": "常见肉类"},
    {"name": "猪肉", "category": "肉类", "description": "常见肉类"},
    {"name": "羊肉", "category": "肉类", "description": "常见肉类"},
    {"name": "鸡肉", "category": "肉类", "description": "常见肉类"},
    {"name": "鸭肉", "category": "肉类", "description": "常见肉类"},
    {"name": "火腿", "category": "肉类", "description": "加工肉类"},
    
    # 粮食类
    {"name": "大米", "category": "粮食", "description": "常见粮食"},
    {"name": "面粉", "category": "粮食", "description": "常见粮食"},
    {"name": "小麦", "category": "粮食", "description": "常见粮食"},
    {"name": "玉米", "category": "粮食", "description": "常见粮食"},
    {"name": "高粱", "category": "粮食", "description": "常见粮食"},
    
    # 饮料类
    {"name": "咖啡", "category": "饮料", "description": "常见饮料"},
    {"name": "茶", "category": "饮料", "description": "常见饮料"},
    {"name": "果汁", "category": "饮料", "description": "常见饮料"},
    {"name": "可乐", "category": "饮料", "description": "常见饮料"},
    
    # 电子产品类
    {"name": "手机", "category": "电子产品", "description": "常见电子产品"},
    {"name": "电脑", "category": "电子产品", "description": "常见电子产品"},
    {"name": "平板", "category": "电子产品", "description": "常见电子产品"},
    {"name": "耳机", "category": "电子产品", "description": "常见电子产品"}
]

def init_brand_config():
    """初始化品牌配置"""
    db = SessionLocal()
    try:
        # 检查是否已有数据
        if db.query(BrandConfig).count() > 0:
            logger.info("品牌配置表已有数据，跳过初始化")
            return
        
        # 导入品牌数据
        brand_objs = []
        for brand in BRANDS:
            # 确定品牌类别
            category = "其他"
            if BRANDS.index(brand) < 15:
                category = "食品饮料"
            elif BRANDS.index(brand) < 26:
                category = "日用品"
            elif BRANDS.index(brand) < 43:
                category = "电子产品"
            elif BRANDS.index(brand) < 54:
                category = "服装"
            elif BRANDS.index(brand) < 65:
                category = "化妆品"
            
            brand_obj = BrandConfig(
                name=brand,
                category=category,
                is_active=True
            )
            brand_objs.append(brand_obj)
        
        db.add_all(brand_objs)
        db.commit()
        logger.info(f"成功导入 {len(brand_objs)} 个品牌配置")
    except Exception as e:
        db.rollback()
        logger.error(f"初始化品牌配置失败: {str(e)}")
    finally:
        db.close()

def init_common_product_names():
    """初始化商品名称排除表"""
    db = SessionLocal()
    try:
        # 检查是否已有数据
        if db.query(CommonProductName).count() > 0:
            logger.info("商品名称排除表已有数据，跳过初始化")
            return
        
        # 导入商品名称
        product_name_objs = []
        for item in COMMON_PRODUCT_NAMES:
            product_name_obj = CommonProductName(
                name=item["name"],
                category=item["category"],
                description=item["description"],
                is_active=True
            )
            product_name_objs.append(product_name_obj)
        
        db.add_all(product_name_objs)
        db.commit()
        logger.info(f"成功导入 {len(product_name_objs)} 个商品名称排除项")
    except Exception as e:
        db.rollback()
        logger.error(f"初始化商品名称排除表失败: {str(e)}")
    finally:
        db.close()

def init_unit_config():
    """初始化单位配置"""
    db = SessionLocal()
    try:
        # 检查是否已有数据
        if db.query(UnitConfig).count() > 0:
            logger.info("单位配置表已有数据，跳过初始化")
            return
        
        # 导入单位数据
        unit_objs = []
        for unit in UNITS:
            # 确定单位类别
            unit_type = "数量单位"
            if UNITS.index(unit) >= 20 and UNITS.index(unit) < 32:
                unit_type = "重量单位"
            elif UNITS.index(unit) >= 32 and UNITS.index(unit) < 40:
                unit_type = "长度单位"
            elif UNITS.index(unit) >= 40:
                unit_type = "体积单位"
            
            unit_obj = UnitConfig(
                name=unit,
                type=unit_type,
                is_active=True
            )
            unit_objs.append(unit_obj)
        
        db.add_all(unit_objs)
        db.commit()
        logger.info(f"成功导入 {len(unit_objs)} 个单位配置")
    except Exception as e:
        db.rollback()
        logger.error(f"初始化单位配置失败: {str(e)}")
    finally:
        db.close()

def init_marketing_word_config():
    """初始化营销词配置"""
    db = SessionLocal()
    try:
        # 检查是否已有数据
        if db.query(MarketingWordConfig).count() > 0:
            logger.info("营销词配置表已有数据，跳过初始化")
            return
        
        # 导入营销词数据
        word_objs = []
        for word in REMOVE_WORDS:
            # 确定词语类别
            category = "其他"
            if REMOVE_WORDS.index(word) < 13:
                category = "促销词"
            elif REMOVE_WORDS.index(word) < 27:
                category = "描述词"
            elif REMOVE_WORDS.index(word) < 38:
                category = "时间词"
            
            word_obj = MarketingWordConfig(
                word=word,
                category=category,
                is_active=True
            )
            word_objs.append(word_obj)
        
        db.add_all(word_objs)
        db.commit()
        logger.info(f"成功导入 {len(word_objs)} 个营销词配置")
    except Exception as e:
        db.rollback()
        logger.error(f"初始化营销词配置失败: {str(e)}")
    finally:
        db.close()

def init_system_config():
    """初始化系统配置"""
    db = SessionLocal()
    try:
        # 检查是否已有数据
        if db.query(SystemConfig).count() > 0:
            logger.info("系统配置表已有数据，跳过初始化")
            return
        
        # 导入系统配置
        configs = [
            {
                "key": "SPECIFICATION_PATTERN",
                "value": SPECIFICATION_PATTERN,
                "description": "规格匹配模式，用于从商品名称中提取规格信息"
            },
            {
                "key": "BRAND_CHAR_RANGE",
                "value": BRAND_CHAR_RANGE,
                "description": "品牌匹配的字符范围，用于从商品名称中提取品牌信息"
            },
            {
                "key": "BRAND_MAX_LENGTH",
                "value": "3",
                "description": "品牌名称最大长度，用于限制从商品名称中提取的品牌长度"
            }
        ]
        
        config_objs = []
        for config in configs:
            config_obj = SystemConfig(
                key=config["key"],
                value=config["value"],
                description=config["description"]
            )
            config_objs.append(config_obj)
        
        db.add_all(config_objs)
        db.commit()
        logger.info(f"成功导入 {len(config_objs)} 个系统配置")
    except Exception as e:
        db.rollback()
        logger.error(f"初始化系统配置失败: {str(e)}")
    finally:
        db.close()

def init_all():
    """初始化所有配置"""
    logger.info("开始初始化配置数据...")
    init_brand_config()
    init_common_product_names()
    init_unit_config()
    init_marketing_word_config()
    init_system_config()
    logger.info("配置数据初始化完成")

if __name__ == "__main__":
    init_all() 